import { login } from '@/request/user'
import { Message } from 'ant-design-vue';
import router, { createRouter } from '@/router/index.js'
import { Local } from '@/util/storage/storage.js'
import { Session } from '@/util/storage/session.js'
// import { getRegisteredUser } from "@/request/user";
import { getTeacherList } from '@/request/teacher'
const state = {
  userInfoSessionName: 'userInfo',
  userInfo: {
    // token: true,
    // email: 'email@qq.asd',
    // mPhone: 13333222321,
    // regName: 'zxc',
    // roleFlag: 2,
  },
  userList: [],
}

const mutations = {
  changeUserInfo(state, payload) {
    state.userInfo = Object.assign({}, state.userInfo, payload)
  },
  // 添加用户信息设置sessionStorage
  setUserinfolocaStorage(state, payload) {
    if (payload.isRemember) {
      Local.set(payload.key, payload.val, true, 60 * 24 * 7)
      Local.set('UTO', Date.now() + 1000 * 60 * (60 * 24 * 7))
      Session.set(payload.key, payload.val, true, 60 * 24)
    } else {
      Local.set(payload.key, payload.val, true, 60 * 6 * 7)
      Local.set('UTO', Date.now() + 1000 * 60 * (60 * 6 * 7))
      Session.set(payload.key, payload.val, true, 60 * 6)
    }
  },
  // 移除浏览器中的sessionStorage用户信息 
  removeUserinfolocaStorage(state, payload) {
    Local.remove(state.userInfoSessionName)
    Local.remove("UTO")
  },
  removeUserinfoSessionStorage(state, payload) {
    Session.remove(state.userInfoSessionName)
    Session.remove('userInfo__expires__')
  },
  // 自定义cookies
  setCookies(state, payload) {
    let exp = new Date();
    exp.setTime(exp.getTime() + 1 * 24 * 60 * 60 * 1000);
    document.cookie = `${payload.name}=` + JSON.stringify(payload.val) + ";expires=" + exp.toGMTString() + ";path=/"
  },
  // 检查是否登录
  checkUserIslogin(state, payload) {
    return new Promise((resolve, reject) => {
      if (!state.userInfo.accessToken) {
        const _this = payload
        _this.$antdMessage.error({
          content: "您还未登录！",
        });
        router.push({
          name: 'Login',
          params: {
            routeName: _this.$route.name,
            query: _this.$route.query
          }
        })
        resolve(false)
      } else {
        resolve(true)
      }
    })
  },
  // 解码用户信息后设置VUEX的userInfo
  useDeCodeSetUserInfo(state, payload) {
    if (payload.roleFlag) {
      var Role = { '大学生': 1, '教师': 2, '中小学生': 4, '家长': 8, '招聘企业': 16, '导师': 32, '课程设计师': 64, '教务': 128, '社会学员': 256, '企业团购学员': 512 }
      let authNum = []
      let authName = []
      Object.keys(Role).forEach(key => {
        if (Role[key] & payload.roleFlag) {
          authNum.push(Role[key])
          authName.push(key)
        }
      })
      payload['authNum'] = authNum
      payload['authName'] = authName
    }

    // 将用户身份信息合并到userInfo
    state.userInfo = Object.assign({}, state.userInfo, payload)
    // this.commit("changeUserInfo", payload); // 当前状态modules引入后 this.commit无法正常使用
  },
  // 修改获取的用户列表
  handleChangeUserList(state, payload) {
    state.userList = payload
  }
}

const actions = {
  Login({
    commit,
    state,
    dispatch
  }, val) {
    const that = val.this
    const params = val.params
    return new Promise((resolve, reject) => {
      login(params)
        .then((res) => {
          if (res.errno === 0) {
            Message.success({
              content: "登录成功",
            });
            commit('setUserinfolocaStorage', { key: state.userInfoSessionName, val: res.data, isRemember: val.params.isRemember })
            commit('useDeCodeSetUserInfo', res.data)
            dispatch('handleGenerateRoutes')
            dispatch('courses/getMyCourses', { that: that }, { root: true })
            resolve(true)
          } else {
            resolve(false)
            Message.error({
              // 后端返回的错误信息 需要更详细的信息
              content: res.message || "登录失败，请联系管理员！",
            });
          }
        })
        .catch((err) => {
          Message.error({ content: err, });
          resolve(false)
        });
    })
  },
  // 退出登录
  Logout({
    commit,
    dispatch
  }) {
    commit('changeUserInfo', {
      name: '',
      accessToken: '',
      refreshToken: '',
      authNum: [],
      authName: [],
    })
    // 清空所有我的课程
    dispatch('courses/removeMyAllCourse', null, { root: true })
    // 删除浏览器的个人信息
    commit('removeUserinfolocaStorage')
    commit('removeUserinfoSessionStorage')
    // dispatch('tagsView/delAllViews', null, { root: true })
    if (router.currentRoute.name !== 'Home') {
      router.push({
        name: 'Home'
      })
    }
  },
  // 获取cookie
  getSession({
    commit,
    dispatch
  }, name) {
    return Session.get(name)
  },
  // getLocalStorage({ commit, dispatch }, name) {
  //   return Local.get(name)
  // },
  // 获取缓存用户信息
  // async getLocalUserInfo({ commit, dispatch }, name) {
  //   const res = Session.get(name, true)
  //   return res ? res : undefined;
  // },
  // 重新获取用户信息
  reacquireUserInfo({ state, commit, dispatch }, params) {
    let newUserInfo = Object.assign({}, state.userInfo, params);
    commit("changeUserInfo", newUserInfo)
    // commit("useDeCodeSetUserInfo", newUserInfo);
    commit("setUserinfolocaStorage", { key: state.userInfoSessionName, val: state.userInfo })
  },
  // 根据身份权限设置添加动态路由
  async handleGenerateRoutes({ state, dispatch }) {
    const roles = state.userInfo.authNum
    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  },
  // 获取用户列表
  async getUserList({ state, commit }, setTeacherAuth) { // setTeacherAuth赋予教师权限 
    let roleFlag = 0;
    if (state.userInfo.authNum.indexOf(2) !== -1 || setTeacherAuth) {
      roleFlag = 2;
    } else if (state.userInfo.authNum.indexOf(32) !== -1) {
      roleFlag = 32;
    } else if (state.userInfo.authNum.indexOf(64) !== -1) {
      roleFlag = 64;
    } else {
      return Message.warning({
        content: "您没有权限获取用户列表!",
      });
    }
    const data = await getTeacherList({ roleFlag: roleFlag });
    if (data) {
      commit("handleChangeUserList", data)
      return data
    }
    else Message.error({ content: "获取教师列表失败" });
  },
}

const getters = {
  getUserInfo(state) {
    return state.userInfo
  }
}



export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}